package com.mathdroid.gui.profile;

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JTextField;

import com.mathdroid.gui.ImageLoader;
import com.mathdroid.gui.main.Popup;
import com.mathdroid.model.Model;
import com.mathdroid.model.Profile;
import com.mathdroid.model.Profiles;
import com.mathdroid.persistence.Serializer;

/**
 * A popup like frame to save a profile under another name.
 */
public class SaveAs extends Popup {
	/**
	 * Default UID.
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * The image loader.
	 */
	private final ImageLoader il = new ImageLoader();

	/**
	 * Create a new "Save as..." popup.
	 * @param parent The parent UI component to align to.
	 */
	public SaveAs(final Component parent) {
		super(parent);
	
		final JTextField nameField = new JTextField();
		nameField.setBackground(this.getPanel().getBackground());
		nameField.setBorder(BorderFactory.createTitledBorder("Profile name"));
		
		final int spacing = 10;
		this.getConstraints().gridx = 0;
		this.getConstraints().gridy = 0;
		this.getConstraints().gridwidth = 2;
		this.getConstraints().insets = new Insets(
				spacing, spacing, spacing, spacing);
		this.getConstraints().fill = GridBagConstraints.HORIZONTAL;
		this.getPanel().add(nameField, this.getConstraints());
		
		
		this.getConstraints().gridx = 0;
		this.getConstraints().gridy = 1;
		this.getConstraints().gridwidth = 1;
		this.getConstraints().insets = new Insets(0, spacing, spacing, spacing);
		JButton create = new JButton("Create");
		create.setIcon(this.il.getImage("add"));
		create.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(final ActionEvent e) {
				String name = nameField.getText();
				Serializer s = new Serializer();
				Profiles profiles = s.getProfiles();
				Profile p = Model.getProfile();
				
				p.setName(name);
				
				profiles.put(name, p);
				
				s.serialize(profiles);
				
				dispose();
			}
		});
		this.getPanel().add(create, this.getConstraints());
		
		this.getConstraints().gridx = 1;
		this.getConstraints().insets = new Insets(0, spacing, spacing, spacing);
		JButton close = new JButton("Close");
		close.setIcon(this.il.getImage("cross"));
		close.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(final ActionEvent e) {
				dispose();
			}
		});
		this.getPanel().add(close, this.getConstraints());
		
		this.pack();
		this.setVisible(true);
	}
}
